package com.neteast.androidclient.newscenter.service;

import java.util.HashSet;
import java.util.List;
import com.neteast.androidclient.newscenter.Global;
import com.neteast.androidclient.newscenter.NewsCenter;
import com.neteast.androidclient.newscenter.R;
import com.neteast.androidclient.newscenter.activity.MainActivity;
import com.neteast.androidclient.newscenter.db.InfoDao;
import com.neteast.androidclient.newscenter.util.ConfigUtil;
import com.neteast.androidclient.newscenter.util.DeBugUtil;
import com.neteast.androidclient.newscenter.util.LoginUtil;
import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.DebugUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.TextView;
/**
 * 本服务的作用是管理桌面上消息盒子图标的显示及隐藏
 * @author tiangh
 *
 */
public class WidgetService extends Service implements Runnable, OnClickListener{

	private ActivityManager am;
	private WindowManager wm;
	private Thread widgetThread;
	private NewsCenter newsCenter;
	
	private Point point;
	public static View newsCenterWidget;
	private TextView totalNews;
	
	private static HashSet<String> pname=new HashSet<String>();
	public static int[] NewsNums=new int[]{0,0,0};
	public static int pressBtn=R.id.btn_sys;
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		newsCenter = ((NewsCenter)getApplication());
		newsCenter.widgetService=this;
		
		setExceptName();
		am=(ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		wm = (WindowManager) getSystemService(WINDOW_SERVICE);
		initWidget();
		newsCenterWidget.setOnClickListener(this);
		widgetThread=new Thread(this);
		widgetThread.start();
	}
	/**
	 * 设置哪些例外的包名(即在这些应用里，小图标依然显示)
	 * 包括桌面和自定义桌面
	 */
	private void setExceptName() {
		PackageManager pm =getPackageManager();
    	Intent intent=new Intent();
    	intent.setAction(Intent.ACTION_MAIN);
    	intent.addCategory(Intent.CATEGORY_HOME);
    	List<ResolveInfo> activities = pm.queryIntentActivities(intent, PackageManager.GET_ACTIVITIES|PackageManager.GET_UNINSTALLED_PACKAGES);
    	if (activities.size()==0) {
		}else {
	    	for (ResolveInfo resolveInfo : activities) {
	    		pname.add(resolveInfo.activityInfo.packageName);
			}
		}
    	//这是为了测试用
		pname.add("com.tgh.test.console");
	}

	/**
	 * 初始化桌面消息盒子的图标
	 */
	private void initWidget() {
		newsCenterWidget = LayoutInflater.from(newsCenter).inflate(R.layout.newscenter_widget, null);
		totalNews = (TextView) newsCenterWidget.findViewById(R.id.total_news);
		
		WindowManager.LayoutParams params=new WindowManager.LayoutParams();
		params.type=WindowManager.LayoutParams.TYPE_PHONE;
		params.flags=WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|
				WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING;
		params.width=(int) (41*newsCenter.screenDensity);
		params.height=(int) (90*newsCenter.screenDensity);
		params.format=PixelFormat.TRANSPARENT;
		point = newsCenter.basePoint;
		params.x=point.x;
		params.y=(int) (point.y+110*newsCenter.screenDensity);
		wm.addView(newsCenterWidget, params);
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		userId = LoginUtil.getUserId(getApplicationContext());
		createUserTable();
		showTotalNewsNum();
		return super.onStartCommand(intent, flags, startId);
	}

	private void createUserTable() {
		InfoDao dao=new InfoDao(getApplicationContext());
		dao.open();
		if (LoginUtil.isNewUser(getApplicationContext(), userId)) 
			dao.createUserTable(userId);
		dao.close();
	}


	public void showTotalNewsNum() {
		int num=0;
		num=NewsNums[1]+NewsNums[2];
		if (!ConfigUtil.getCloseBroadcastNotify(newsCenter, userId)) {
			num+=NewsNums[0];
		}
		totalNews.setText(num+"");
		totalNews.setVisibility(View.INVISIBLE);
		if (num>0) {
			totalNews.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 判断当前是否是在桌面，若是桌面，返回true，若是其他应用程序，返回false
	 * @return
	 */
	private boolean isLauncher(){
		String packageName = am.getRunningTasks(2).get(0).topActivity.getPackageName();
		if (pname.contains(packageName)) {
			return true;
		}
		return false;
	}
	
	
	/**
	 * 设置消息盒子的可见性
	 */
	public void setWidgetVisible() {
		//当处于桌面，而消息盒子不可见，那么设置其为可见
		if (isLauncher()) {
			if (newsCenterWidget.getVisibility()==View.GONE) {
				newsCenterWidget.setVisibility(View.VISIBLE);
			}
			showTotalNewsNum();
		}else{
		//当不是处于桌面，而消息盒子又可见，设置其为不可见
			if (newsCenterWidget.getVisibility()==View.VISIBLE) {
				newsCenterWidget.setVisibility(View.GONE);
			}
		}
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		run=false;
		wm.removeViewImmediate(newsCenterWidget);
		newsCenterWidget=null;
		pname.clear();
		pname=null;
	}
	boolean run=true;
	@Override
	public void run() {
		while(run){
			handler.sendEmptyMessage(Global.HANDLER_CHECK_NEWSCENTER_VISIBLE);
			try {
				Thread.sleep(1200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	private Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Global.HANDLER_CHECK_NEWSCENTER_VISIBLE:
				setWidgetVisible();
				break;
			}
		}
	};
	private int userId;
	@Override
	public void onClick(View v) {
		openNewsList();
	}
	/**
	 * 打开消息列表
	 */
	public void openNewsList(){
		NewsNums[0]=0;
		pressBtn=R.id.btn_sys;
		Intent intent=new Intent(getApplicationContext(), MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}
	
	public void hiddenNewsList() {
		newsCenterWidget.setVisibility(View.GONE);
	}
}
